package com.probiz.estore.eai.common;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.probiz.estore.common.model.eai.log.EaiJobLog;
import com.probiz.estore.core.util.I18nUtil;
import com.probiz.estore.core.util.SchedulerUtil;
import com.probiz.estore.eai.log.service.EaiJobLogManager;
import com.probiz.estore.system.scheduler.service.JobListenerImpl;

public class EaiJobListenerImpl extends JobListenerImpl{
	private final static Log logger	= LogFactory.getLog(EaiJobListenerImpl.class);
	
	private EaiJobLogManager eaiJobLogManager = null;
	
	public void setEaiJobLogManager(EaiJobLogManager eaiJobLogManager) {
		this.eaiJobLogManager = eaiJobLogManager;
	}


	@Override
	public void jobWasExecuted(JobExecutionContext context,
			JobExecutionException jobException) {
		EaiJobLog eaiJobLog = new EaiJobLog();
		eaiJobLog.setJobName(I18nUtil.getInstance().getMessage(context.getTrigger().getFullName()));
		eaiJobLog.setJobExecuteTime(context.getScheduledFireTime());
		
		if (jobException != null) {
			// 记录错误
			SchedulerUtil.addErrorJob(context.getTrigger().getName(), jobException);
			logger.error(jobException);
			//reportEmail(context, jobException);
			
			//提取异常链的末端
			Throwable throwable = jobException;
			while(throwable.getCause()!=null){
				throwable = throwable.getCause();
			}
			
			eaiJobLog.setStatus(EaiJobLog.STATUS_FAILED);
			eaiJobLog.setErrorMessage(throwable.getMessage());
			
		} else {
			SchedulerUtil.removeErrorJob(context.getTrigger().getName());
			
			eaiJobLog.setStatus(EaiJobLog.STATUS_SUCCESS);
		}
		
		//日志记录到数据库
		eaiJobLogManager.save(eaiJobLog);
	}

	
}
